import Konva from 'konva'
import cloneDeep from 'lodash.clonedeep'
import { useState } from 'react'

// 自定义Hook：处理图形选择逻辑
export const useShapeSelection = () => {
  const [selectedIds, setSelectedIds] = useState<string[]>([])

  // 处理图形点击选择
  const handleShapeClick = (e: Konva.KonvaEventObject<MouseEvent>, isTransformerMode: boolean) => {
    if (isTransformerMode) return

    const node = e.target as Konva.Shape
    const id = node.id()
    const isShiftPressed = e.evt.shiftKey

    setSelectedIds(prev => {
      const newSelectedIds = cloneDeep(prev)
      const index = newSelectedIds.indexOf(id)

      if (index === -1) {
        // 如果按住Shift键，则添加到已选中列表；否则替换已选中列表
        return isShiftPressed ? [...newSelectedIds, id] : [id]
      } else {
        // 如果已经选中，则取消选中
        newSelectedIds.splice(index, 1)
        return newSelectedIds
      }
    })
  }

  // 处理舞台点击，清除选择
  const handleStageClick = (e: Konva.KonvaEventObject<MouseEvent>) => {
    if (e.target === e.target.getStage()) {
      setSelectedIds([])
    }
  }

  return { selectedIds, setSelectedIds, handleShapeClick, handleStageClick }
}
